import { login, getInfo ,send_Code} from '@/api/user'
import { setValue, getValue } from '@/libs/util'
import mqtt from '../../libs/mqtt';
import chat from '../module/chat'

export default {
    state: {
        token: getValue('loginInfo').token,
        userId: getValue('loginInfo').userId,
        clientId: getValue('client').clientId,
        userInfo:{}
    },
    mutations: {
        // 存储clientId
        setClientId(state, client){
            state.clientId = client.clientId
            setValue("client",client)
        },
        // 登录token userid存储
        setLoginInfo(state, loginInfo) {
            state.token = loginInfo.token
            state.userId = loginInfo.userId
            setValue("loginInfo",loginInfo)
        },
        // 用户信息
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo
            chat.state.user.userId = userInfo.uid
            chat.state.user.portrait = userInfo.portrait
            chat.state.user.name = userInfo.name
            setValue("userInfo",userInfo)
        }
    },
    actions: {
        // 登陆
        handleLogin ({ commit }, parm) {
            let _this = this
            return new Promise((resolve, reject) => {
                login(parm).then(data => {
                    if(data.code === 0){
                        let res = data.result
                        commit('setClientId',{'clientId':parm.clientId})
                        commit('setLoginInfo', res)
                        // 连接mqtt
                        mqtt.initMqtt()
                    }
                    resolve(data)
                }).catch(err => {
                    reject(err)
                })
            })
        },
        // 获取用户信息
        getUserInfo ({state, conmmit}) {
            return new Promise((resolve, reject) => {
                getInfo({userId: state.userId}).then(data => {
                    if(data.code === 0){
                        let res = data.result
                        console.log("用户信息：",res)
                    }
                    resolve()
                }).catch(err => {
                    reject(err)
                })
            })
        },
      //获取验证码
      sendCode(state,parm){
        return new Promise((resolve, reject) => {
          send_Code({
            mobile:parm,
            countryCode:86,
            smsType:1
          }).then(data => {
            if(data.code === 0){
              // console.log("用户信息：",data.message)
            }
            resolve(data)
          }).catch(err => {
            reject(err)
          })
        })
      }
    }
}
